﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MadPropsDemo.Tests
{
    static class ReflectionUtils
    {
        public static void ReplaceMember<T>(object target, T newValue)
        {
            var fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            var field = fields.Where(f => f.FieldType == typeof(T)).SingleOrDefault();

            if (field == null)
            {
                field = fields.Where(f => f.FieldType.IsAssignableFrom(typeof(T)) && f.FieldType != typeof(object)).SingleOrDefault();
            }

            if (field == null)
            {
                throw new Exception("Ambiguous - did not find exactly one field of type " + typeof(T));
            }

            field.SetValue(target, newValue);
        }
    }
}
